﻿using CommonNet48.LogUtils.Log4net;
using System;
using System.Diagnostics;
using System.IO;

namespace CommonNet48.Net
{
    /// <summary>
    /// Windows共享帮助类
    /// </summary>
    public class WinShareHelper
    {
        /// <summary>
        /// 日志操作对象
        /// </summary>
        private static readonly Log4 _Logger = new Log4(typeof(WinShareHelper));

        /// <summary>
        /// 连接远程共享文件夹
        /// </summary>
        /// <param name="path">远程共享文件夹的路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <returns></returns>
        public static bool ConnectShareServer(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                _Logger.Error($"连接服务器失败！\r\n{ex.Message}", ex);
                return false;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fPath">下载文件完整路径</param>
        /// <param name="savePath">本地保存路径</param>
        /// <param name="username">用户名</param>
        /// <param name="passWord">密码</param>
        /// <param name="act_Progress">进度处理委托。参数1为当前接收大小，参数2为下载文件总大小,参数3为用时(毫秒),参数4为速度(kb/s)</param>
        /// <returns></returns>
        public static bool DownloadFile(string fPath, string savePath, string username, string passWord, Action<long, long, long, decimal> act_Progress)
        {
            FileStream fs = null;
            long startpos;
            try
            {
                string fDir = Path.GetDirectoryName(fPath);
                if (!ConnectShareServer(fDir, username, passWord)) return false;
                string dirName = Path.GetDirectoryName(savePath);
                string fileName = Path.GetFileName(savePath);
                string tempSaveFileName = Path.Combine(dirName, $"{fileName}.temp");
                if (File.Exists(tempSaveFileName))
                {
                    fs = File.OpenWrite(tempSaveFileName);
                    startpos = fs.Length;
                    fs.Seek(startpos, SeekOrigin.Current);
                }
                else
                {
                    if (!Directory.Exists(dirName))
                    {
                        Directory.CreateDirectory(dirName);
                    }
                    fs = new FileStream(tempSaveFileName, FileMode.Create);
                    startpos = 0;
                }

                using (Stream stream = File.OpenRead(fPath))
                {
                    long totalsize = stream.Length;
                    long currsize = startpos;
                    if (startpos > 0) stream.Seek(startpos, SeekOrigin.Current);
                    if (currsize > totalsize) throw new Exception("下载文件大小匹配异常，请重新下载！");
                    Stopwatch watch = Stopwatch.StartNew();
                    byte[] buffer = new byte[10240];
                    int readsize = stream.Read(buffer, 0, buffer.Length);
                    int recCount = readsize;//接收数据长度
                    long saveseconds = watch.ElapsedMilliseconds;//记录本次速度计算起始时间
                    decimal speed = 0;//速度
                    act_Progress?.Invoke(currsize, totalsize, watch.ElapsedMilliseconds, speed);
                    while (readsize > 0)
                    {
                        fs.Write(buffer, 0, readsize);
                        currsize += readsize;
                        if (currsize > totalsize) throw new Exception("下载文件大小匹配异常，请重新下载！");
                        long speedcalctime = watch.ElapsedMilliseconds - saveseconds;
                        if (speedcalctime > 1000)
                        {
                            speed = (recCount / 1024m) / (speedcalctime / 1000m);
                            saveseconds = watch.ElapsedMilliseconds;
                            recCount = 0;
                        }
                        act_Progress?.Invoke(currsize, totalsize, watch.ElapsedMilliseconds, speed);
                        readsize = stream.Read(buffer, 0, buffer.Length);
                        recCount += readsize;
                    }
                    watch.Stop();
                    fs.Close();
                    stream.Close();
                    File.Move(tempSaveFileName, savePath);
                    return true;
                }
            }
            catch (Exception ex)
            {
                fs?.Close();
                _Logger.Error($"下载文件发生异常！\r\n{ex.Message}", ex);
                return false;
            }
        }
    }
}
